// 利用颜色和位置转换，快速判断一个点是否位于多边形内部
/**
 * 
 * @param {number} width 
 * @param {number} height 
 * @param {Array<[number, number]>} polygon
 */
function FastPip(width, height, polygon) {
  const canvas = document.createElement('canvas')
  canvas.width = width
  canvas.height = height
  // 将polygon绘制在canvas上
  const ctx = canvas.getContext('2d')
  ctx.beginPath()
  const polygonColor = "rgba(0, 0, 0, 255)"
  const bgColor = "rgba(0, 255, 0, 255)"
  // 绘制背景
  ctx.fillStyle = bgColor
  ctx.fillRect(0, 0, width, height)
  for (let i = 0; i < polygon.length; i++) {
    const [x, y] = polygon[i]
    if (i === 0) {
      ctx.moveTo(x, y)
    } else {
      ctx.lineTo(x, y)
    }
  }
  ctx.closePath()
  // 绘制多边形
  ctx.fillStyle = polygonColor
  ctx.fill()
  document.body.appendChild(canvas)
  // 获取imageData
  const imgData = ctx.getImageData(0, 0, width, height)
  const width_ = imgData.width
  const height_ = imgData.height
  const pixels = imgData.data
  return (x, y) => {
    // bound
    const transX = x < 0 ? 0 : x > width_ ? width_: x
    const transY = y < 0 ? 0 : y > height_ ? height_ : y 
    // 计算pixels中的索引
    const index = (width_ * transY + transX) * 4
    // 获取rgba
    const r = pixels[index]
    const g = pixels[index + 1]
    const b = pixels[index + 2]
    const a = pixels[index + 3]
    return r === 0 && g === 0 && b === 0 && a === 255
  }
}